/*
 * @Author: your name
 * @Date: 2021-09-03 11:26:07
 * @LastEditTime: 2021-11-26 16:33:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /柳橙/拆单红冲/yongyou_zj5j_separatebill/src/http/index.js
 */
import Axios from 'axios';
import { router } from '../main';
import { Message, Loading } from 'element-ui';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
  showSpinner: true, // 是否显示加载ico
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.3, // 初始化时的最小百分比
});

Axios.defaults.timeout = 5000; // 响应时间
Axios.defaults.baseURL = process.env.VUE_APP_APIURL;
Axios.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    window.combineHeader(config.headers);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

Axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  },
);

/**
 * 公共请求入口
 * @param param 'object'
 * @param url   'string'
 * @param type  'get || post'
 * @returns {Promise}
 */
export const commonPromise = ({ data, params, url, method = 'get' }) => {
  if (url.includes('sso') || url.includes('sys/authority')) {
    Axios.defaults.baseURL = 'https://wei.cscec5b.com.cn:9067/gateway/'
  } else {
    Axios.defaults.baseURL = process.env.VUE_APP_APIURL;
  }

  NProgress.start();
  const option = {
    lock: true,
    // text: 'Loading...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, .2)',
    customClass: "osloading",
  }
  let loadingInstance = Loading.service(option);

  return new Promise((resolve, reject) => {
    Axios({
      url,
      method,
      data,
      params,
    })
      .then((res) => {
        if (res.status === 200) {
          // 成功
          NProgress.done();
          if (res.data.code === 0) {
            resolve(res.data);
            console.timeEnd();
          } else if (res.data.code === 400 || res.data.code === 403 || res.data.code === 1001 || res.data.code === 1004 || res.data.code === 500) {
            // localStorage.removeItem("sessionId");
            // localStorage.removeItem("userInfo");
            const message = res.data.message.replace(',', '\n')
            res.data.message && Message({ type: 'error', dangerouslyUseHTMLString: true, message: `<span style="white-space:pre-line;line-height: 18px">${message}</span>` });;

            // router.push('/error/404');
            // reject(new Error('用户状态变更'));
          } else {
            // Message.error(res.data.msg || res.data.Message);
            // reject(res.data.msg || res.data.Message);
            resolve(res.data);
          }
        } else if (res.status === 403) {
          // 用户状态变更
          localStorage.removeItem('sessionId');
          localStorage.removeItem('userInfo');
          res.data.msg && Message.error(res.data.msg);

          router.push('/error/404');
          // reject(new Error("用户状态变更"));
        } else {
          res.data.msg && Message.error(res.data.msg);
          reject(new Error('系统出错'));

        }
        loadingInstance.close()
      })
      .catch((err) => {
        loadingInstance.close()
        console.log(err);
        NProgress.done();
        Message.error('系统出错');
        reject(err);
      });
  });
};
